package com.atom.common.web.controller;

import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.atom.common.remote.file.RemoteFileDao;
import com.atom.common.remote.user.UserUtil;
import com.atom.common.util.JsonUtil;

@Controller
@RequestMapping("remote/file")
public class RemoteFileController {
  
  private static Logger logger = Logger.getLogger(RemoteFileController.class);
  
  @Resource RemoteFileDao remoteFileDao;
  private static final String SUCCESS = "操作成功";
  private static final String FAIL = "操作失败";
  
  @RequestMapping(method=RequestMethod.GET, value="deleteRemoteFile.do")
  @ResponseBody
  public String deleteRemoteFile(@RequestParam(value = "key", required = true) String key) {
    try {
      remoteFileDao.delete(key);
      return SUCCESS;
    } catch (Exception e) {
      logger.error("error message = {}" + e.getMessage(), e);
      return FAIL;
    }
  }
  
  @RequestMapping(method=RequestMethod.GET, value="deleteRemoteFileWithoutLocal.do")
  @ResponseBody
  public String deleteRemoteFileWithoutLocal(@RequestParam(value = "key", required = true) String key) {
    try {
      remoteFileDao.delete(key);
      return SUCCESS;
    } catch (Exception e) {
      logger.error("error message = {}" + e.getMessage(), e);
      return FAIL;
    }
  }
  
  @RequestMapping(method=RequestMethod.GET, value="addRemoteFile.do")
  @ResponseBody
  public String addRemoteFile(@RequestParam(value = "processInstanceId", required = true) String processInstanceId,
      @RequestParam(value = "taskId", required = true) String taskId,
      @RequestParam(value = "fileName", required = true) String fileName,
      @RequestParam(value = "fileSize", required = true) String fileSize,
      @RequestParam(value = "key", required = true) String key,
      @RequestParam(value = "fileType", required = true) Integer fileType,
      HttpServletRequest request) {
    Map<String, Object> result = new HashMap<String, Object>();
    try {
      UserUtil user = new UserUtil(request);
      remoteFileDao.add(fileType, taskId, processInstanceId, fileName, key, fileSize, user);
      result.put("data", remoteFileDao.find(processInstanceId, fileType));
      result.put("status", 1);
    } catch (Exception e) {
      logger.error("error message = {}" + e.getMessage(), e);
      result.put("status", 0);
    }
    return JsonUtil.ObjectToJsonQuietly(result);
  }

}
